<?php

jimport('joomla.application.component.controller');

class bgController extends JController {
    
    public function __construct(){
        parent::__construct();
        
        
        $this->model = $this->getModel();
    }
    
    public function display($cachable = false, $urlparams = false) {
        parent::display($cachable, $urlparams);
    }

    public function savetemp(){ 
        
        $body = &JRequest::getVar( 'jform',null, 'post', 'array', JREQUEST_ALLOWHTML );
        // get data form
        $data = &JRequest::getVar('jform');
        $data['MAMA_BODY'] = $body['MAMA_BODY'];
        
        // check addnew or edit
        $addNew = $data['MAMA_CODE'] ? false : true;
        
        $data['MAMA_DATETIME'] = "$data[year]/$data[month]/$data[day] $data[hour]:$data[min]:00";
        // we have three status : 1 save draft, 2 waiting schedule, 3 sent
        $data['MAMA_FLAG'] = 1;
        $data['MAMA_CODE'] = $data['MAMA_CODE'] ? $data['MAMA_CODE'] : HelperBG::getIDAuto('mama', 'MAMA_CODE');
        
        // set senders
        $user = JFactory::getUser();

        $data['MAMA_SENDER'] = $user->username;
        $data['MAMA_TITLE'] = $data['MAMA_TITLE'].' '.$i;
       
        if($this->model->savetemp($data, $addNew)){
            
            $this->setRedirect('index.php?option=com_mail');
        }else{
            JError::raiseError(500, 'エラー！データが記録されません。' );
        }

        parent::display();
    }

    public function save(){
        // hold html for body mail
    	$body = &JRequest::getVar( 'jform',null, 'post', 'array', JREQUEST_ALLOWHTML );
        // get data form
        $data = &JRequest::getVar('jform');
        $data['MAMA_BODY'] = $body['MAMA_BODY'];

        $err = '';
        // error, when MAMA_MAGR_CODE is null and MAMA_MAGR_CODE isn't 3 coacher
        if(!$data['MAMA_MAGR_CODE']){
           // $err .= '<p>配信先を入力してください。</p>';
            $error = " 配信先を入力してください。";                
            JRequest::setVar('task','error');
            JFactory::getApplication()->enqueueMessage($error, 'error');
            parent::display();
            return;
        }
        if(!$data['MAMA_TITLE']){
           // $err .= '<p>件名を入力してください。</p>';
            $error = " 件名を入力してください。";                
            JRequest::setVar('task','error');
            JFactory::getApplication()->enqueueMessage($error, 'error');
            parent::display();
            return;
        }
        if(!$data['MAMA_BODY']){
            //$err .= '<p>メールマガジン本文を入力してください。</p>';
            $error = " メールマガジン本文を入力してください。";                
            JRequest::setVar('task','error');
            JFactory::getApplication()->enqueueMessage($error, 'error');
            parent::display();
            return;
        }
        
        if ($data['MAMA_TYPE'] != 3) {
            $listEmail = $this->validateEmail($data['MAMA_MAGR_CODE']);
        }
       
        if(count($listEmail['error'])){
            $error = '<strong>指定する配信先に不備があります。</strong> : '.implode(', ',$listEmail['error']);
            //$error = " 指定する配信先に不備があります。";                
            JRequest::setVar('task','error');
            JFactory::getApplication()->enqueueMessage($error, 'error');
            parent::display();
            return;
        }
        
      
       // no error
        if(!$err){
            
            // check addnew or edit
            $addNew = $data['MAMA_CODE'] ? false : true;
            
            /** SET DATA */
            if($data['MAMA_TYPE'] == 2){
                $data['MAMA_DATETIME'] = date('Y/m/d H:i:s A');
                //$data['MAMA_DATETIME'] = date("l jS \of F Y h:i:s A");
            }
            elseif ($data['MAMA_TYPE'] == 3) {
                if(date('m',mktime(0, 0, 0, date("m")+1, date("d"), date("Y"))) %12 == 1)
                {
                    $date=date('Y-m-d H:i:s',mktime(0, 0, 0, date("m")-11, 01, date("Y")+1)); 
                }else
                    $date=date('Y-m-d H:i:s',mktime(0, 0, 0, date("m")+1, 01, date("Y")));
                $data['MAMA_DATETIME'] = $date;
            }
             else {
                $data['MAMA_DATETIME'] = "$data[year]/$data[month]/$data[day] $data[hour]:$data[min]:00";
            }
            // we have three status : 1 save draft, 2 waiting schedule, 3 sent
            $data['MAMA_FLAG'] = 2;
            $data['MAMA_CODE'] = $data['MAMA_CODE'] ? $data['MAMA_CODE'] : HelperBG::getIDAuto('mama', 'MAMA_CODE');
            
            // set senders
            $user = JFactory::getUser();
    
            $data['MAMA_SENDER'] = $user->username;
            
            if($data['MAMA_TYPE'] == 3){ // coacher
                 $data['MAMA_MAGR_CODE'] = '指導員更新用';
            }else{
                $data['MAMA_MAGR_CODE'] = str_replace("\n",null,$data['MAMA_MAGR_CODE']);
                $data['MAMA_MAGR_CODE'] = str_replace("\r",null,$data['MAMA_MAGR_CODE']);
            }
    
           /* END SET DATA */
            // var_dump($data);
            // die;
            // save to database and send mail
            if($this->model->savetemp($data, $addNew)){
                
                // sent mail now
                if($data['MAMA_TYPE'] == 2){
                    // sent mail
                    HelperBG::sendMail($listEmail['list'], $data['MAMA_TITLE'], $data['MAMA_BODY'],'email', 'name', $data['MAMA_REJECT']);
                    // die;
                    // update flag = 3 : sent
                    $this->model->updateFlag(3, $data['MAMA_CODE']);  
                }
                
                $this->setRedirect('index.php?option=com_mail');
            }else{
                JError::raiseError(500, 'エラー！データが記録されません。' );
            }
        }else{
            //JError::raiseError(500, $err );
            JRequest::setVar('task','error');
            JFactory::getApplication()->enqueueMessage($err, 'error');
        }
       
      

        parent::display();
    }
    
    public function remove(){
    	$cid = JRequest::getVar('cid');
        if($this->model->remove($cid)){
            $this->setRedirect('index.php?option=com_mail');
        }else{
            JError::raiseError(500, 'エラー！データが記録されません。' );
        }
    }
    
    
    public function validateEmail($Receiver){

    	$Receiver = explode(';', $Receiver);
        
        $list = array();
        $error = array();
        foreach($Receiver as $re){

            if($re){
                // get name , email
                //$re = explode('(', $re);
                $e_name = substr($re, 0, strripos($re,'(', 1)); 
                $e_mail = substr($re, strripos($re,'(', 1)); 
                $re = array();
                $re[0] = $e_name;
                $re[1] = str_replace(')', '', $e_mail);  
                $re[1] = str_replace('(', '', $re[1]);  

                if(!$re[1]){
                    $re[1] = str_replace(' ',null,$re[0]);
                }else{
                    // delete char ')' end
                    $re[1] = str_replace(' ',null,substr($re[1], 0, strlen($re[1])));
                }
                
                if(substr($re[0], 0, 1) == '*'){ // group mail
                    $userType = $this->model->getMAGR_USERTYPE($re[1]);
                    switch($userType){
                        case 0:
                        case 3:
                        case 4:
                            // user system, center, club
                           $listUser = $this->model->getUserSystem($re[1]);   
                        break;
                            
                        case 1:
                            // coacher
                            $listUser = $this->model->getUserCoacher($re[1]);   
                        break;
                        
                        case 2:
                            // out user
                            $listUser = $this->model->getUserOut($re[1]);   
                        break;
                    }
                    
                    // join list and listUser
                    $list = array_merge($list, $listUser);
                   
                }else{ // list user mail
                    //check validate email , if it's true add to $list, else add to $error
                    if($this->validate_email($re[1])){
                        $list[] = array('name'=>$re[0], 'email'=>$re[1]);
                    }else{
                        $error[] = $re[1];
                    }
                }
                
                
            }
            $listEmail = array('list'=>$list, 'error'=>$error);
            //unset($error); unset($Receiver);unset($list);
        }// end foreach

        return $listEmail;
    } // end fucntion
    
    
    function validate_email($e){
        return (bool)preg_match("`^[a-z0-9!#$%&'*+\/=?^_\`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_\`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$`i", trim($e));
    }
}